import { PayloadAction } from '@reduxjs/toolkit';
import { IMenuDataItem, MenuTypeEnum } from 'src/interface';
import { generateMenuTree } from 'src/utils/tools';
import { State } from './initState';
import { permissionRoute } from 'src/router';
import { filterRoutes, preCondition, generateNavigate } from './tools';

export const setMenus = (state: State, action: PayloadAction<IMenuDataItem[]>) => {
  const menuList = action.payload;
  const menuAuthList = [] as string[];
  const btnAuthList = [] as string[];
  const filterMenuList = [] as IMenuDataItem[];

  menuList.forEach((menu) => {
    if (menu.menuType === MenuTypeEnum.BUTTON) {
      menu.permission && btnAuthList.push(menu.permission);
      return;
    }
    if (menu.menuType === MenuTypeEnum.MENU) {
      menu.path && menuAuthList.push(menu.path);
    }
    filterMenuList.push(menu);
  });
  state.buttons = btnAuthList;
  state.menus = menuAuthList;

  state.menuInfo = generateMenuTree(preCondition(filterMenuList));
  const routes = filterRoutes([...permissionRoute], [...menuAuthList]);
  state.defaultOpenPath = generateNavigate(routes);
  state.dynamicRoute = routes;
};
